package com.filter;

import com.MybatisUtil.MybatisUtil;

import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter(urlPatterns = "/*",filterName = "SqlSessionFilter")
public class SqlSessionFilter implements javax.servlet.Filter {
    public void destroy() {
    }

    public void doFilter(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse, javax.servlet.FilterChain filterChain) throws javax.servlet.ServletException, IOException {
        filterChain.doFilter(servletRequest,servletResponse);
        HttpServletRequest hReq = (HttpServletRequest) servletRequest;
        String path = hReq.getServletPath();
        String contentType = hReq.getContentType();
        System.out.println("["+path+"]"+"["+contentType+"]"+"访问");
        if (path != null &&
               ! (path.endsWith("jpg")||
                path.endsWith("png")||
                path.endsWith("gif")||
                path.endsWith("webp")||
                path.endsWith("html")||
                path.endsWith("htm")||
                path.endsWith("woff")||
                path.endsWith("js")||
                path.endsWith("css")
                )){
        try {
            System.out.println("["+path+"]"+"["+contentType+"]"+"open");
            //1.请求
            MybatisUtil.open();
            //2.目标,servlet->dao->DB
            filterChain.doFilter(servletRequest,servletResponse);
        }catch (Exception e){
            MybatisUtil.rollback();
            throw  e;
        }finally {
            //3.响应
            MybatisUtil.close();

            System.out.println("["+path+"]"+"["+contentType+"]"+"close");
        }
        }else {
            filterChain.doFilter(servletRequest,servletResponse);

        }
        System.out.println("["+path+"]"+"["+contentType+"]"+"结束");




    }

    public void init(javax.servlet.FilterConfig config) throws javax.servlet.ServletException {

    }

}
